﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web;
using System.Web.SessionState;

namespace FB.Data
{

    public class SessionRepository<TEntity> where TEntity : class 
    {
        internal List<TEntity> sessionList;
        internal HttpSessionState sessionState;
        internal string sessionKey;

        public SessionRepository()
            : this(typeof(TEntity).Name)
        {
        }

        public SessionRepository(string sessionKey)
            : this(HttpContext.Current.Session, sessionKey)
        {
        }

        public SessionRepository(HttpSessionState session, string sessionKey)
        {
            this.sessionState = session;
            this.sessionKey = sessionKey;
            this.sessionList = (List<TEntity>)sessionState[sessionKey];
            if (this.sessionList == null) { this.sessionList = new List<TEntity>(); }
        }



        public virtual List<TEntity> Get(
            Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null
            )
        {
            IQueryable<TEntity> query = sessionList.AsQueryable();

            if (filter != null)
            {
                query = query.Where(filter);
            }

            return ((orderBy != null) ? orderBy(query) : query).ToList();
        }

        

        public virtual TEntity Insert(TEntity entity)
        {
            sessionList.Add(entity);
            return entity;
        }



        public virtual void Delete(Func<TEntity, bool> filter)
        {
            var entityToDelete = sessionList.Where(filter);
            if (entityToDelete != null && entityToDelete.Count() > 0)
            {
                foreach (var t in entityToDelete)
                {
                    this.sessionList.Remove(t);
                }
            }
        }



        public virtual void Update(Func<TEntity, bool> filter, TEntity entityToUpdate)
        {
            var entity = sessionList.Where(filter).FirstOrDefault();
            if (entity != null)
            {
                sessionList[sessionList.IndexOf(entityToUpdate)] = entity;
            }
        }



        public virtual void SaveChanges()
        {
            sessionState[sessionKey] = this.sessionList;
        }
    }
}

